package server;

import cn.hutool.core.util.ClassLoaderUtil;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;

/**
 * @Author: zhouzhijun
 * @Date: 2021/4/28 14:43
 */
public class MyClassLoader extends ClassLoader {

    private String classPath;

    public MyClassLoader(String classPath) {

        this.classPath = classPath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] bytes;
        Class<?> clazz;
        if (ifPresent(name)) {
            return ClassLoaderUtil.loadClass(name);
        }
        try {
            //获取.class 文件的二进制字节
            bytes = getClassByte(name);
            //将二进制字节转化为Class对象
            clazz = defineClass(name, bytes, 0, bytes.length);
            return clazz;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.findClass(name);
    }


    private byte[] getClassByte(String name) throws IOException {
        String classFile = classPath + File.separator + name.replace(".", File.separator) + ".class";
        return Files.readAllBytes(Path.of(classFile));
    }

    private Boolean ifPresent(String name) {
        try {
            ClassLoaderUtil.loadClass(name);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
